#include "mg_pwm.h"
#include "mg_Device.h"

//蜂鸣器音效
static pthread_t Bee_task;//任务ID
static volatile bool BeeTaskQuit = false;
static void* mg_BeeTask(void* arg);
static uint8_t Bee_Cmd = 0;
static uint8_t Bee_Cmd_dbg = 0;
//PWM初始化
void Bee_Init(void)
{
	ithPwmInit(BEE_PWM, BEE_PWM_Hz, BEE_PWM_DUTY);
	ithPwmEnable(BEE_PWM, BEE_PWM_Pin, BEE_GPIO_MODE);
	ithPwmReset(BEE_PWM, BEE_PWM_Pin, BEE_GPIO_MODE);	
	ithPwmDisable(BEE_PWM, BEE_PWM_Pin);
	pthread_attr_t attr;
	struct sched_param param;
	pthread_attr_init(&attr);
	param.sched_priority = sched_get_priority_min(1) + 2;
	pthread_attr_setschedparam(&attr, &param);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&Bee_task, &attr, mg_BeeTask, NULL);
}
//响"滴"
void Bee_Di(void)
{
	if (Sys_Config.byte.Rotate_Voice !=0x02)
		Bee_Cmd = BEE_CMD_ON;
}

//查询蜂鸣器是否需要响
void Bee_Check_Cmd(void)
{
	if (Bee_Cmd == BEE_CMD_ON)
		ithPwmEnable(BEE_PWM, BEE_PWM_Pin, BEE_GPIO_MODE);
	else
	{
		ithPwmDisable(BEE_PWM, BEE_PWM_Pin);
		Bee_Cmd_dbg = 0;
	}
		
	Bee_Cmd = BEE_CMD_OFF;
}
//专门用于需要演示处理的线程
extern uint32_t volatile Timems;
static void* mg_BeeTask(void* arg)
{
	Timems = 0;
	while (!BeeTaskQuit)
	{
		usleep(500000);
		Timems = 0;
	}
	return NULL;
}
uint8_t report_Bee_Cmd_dbg(void)
{
	return Bee_Cmd_dbg;
}
/*

uint32_t  tick1, tick2;
timer_t Bee_timer_id;
static struct itimerspec Bee_timer_value;
static bool keep_flag = 0;
static void Bee_Timeover_Callback(timer_t timerid, int arg)
{
	ithPwmDisable(BEE_PWM, BEE_PWM_Pin);
	tick2 = SDL_GetTicks();
	keep_flag = 0;
	printf("Moorgen INFO:Bee_Di stop and tick is %d.\n", tick2 - tick1);
}
 
void Bee_Init(void)
{
	ithPwmInit(BEE_PWM, BEE_PWM_Hz, BEE_PWM_DUTY);
	ithPwmEnable(BEE_PWM, BEE_PWM_Pin, BEE_GPIO_MODE);
	ithPwmReset(BEE_PWM, BEE_PWM_Pin, BEE_GPIO_MODE);
	ithPwmDisable(BEE_PWM, BEE_PWM_Pin);

	// 创建定时器
	timer_create(CLOCK_REALTIME, NULL, &Bee_timer_id);
	timer_connect(Bee_timer_id, (VOIDFUNCPTR)Bee_Timeover_Callback, 0);
}
//响"滴"
void Bee_Di(void)
{
	if (Sys_Config.byte.Rotate_Voice != 0x02)
	{
		if (keep_flag != 0)
			return;
		keep_flag = 1;
		tick1 = SDL_GetTicks();
		ithPwmEnable(BEE_PWM, BEE_PWM_Pin, BEE_GPIO_MODE);
		//清定时器计数
		Bee_timer_value.it_interval.tv_sec = 0;
		Bee_timer_value.it_interval.tv_nsec = 0;
		Bee_timer_value.it_value.tv_sec = 0;
		Bee_timer_value.it_value.tv_nsec = BEE_PWM_ON_TIME * 1000;
		if (timer_settime(Bee_timer_id, 0, &Bee_timer_value, NULL) != 0)
			printf("Moorgen INFO:Bee_Di timer_settime is Err\n");
		else
			printf("Moorgen INFO:Bee_Di start.\n");
	}
}
 */